package io.renren.modules.order.controller;

import io.renren.common.utils.R;
import io.renren.modules.order.entity.OrderEntity;
import io.renren.modules.order.service.OrderService;
import io.renren.modules.sys.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/order")
public class OrderController {

    @Autowired
    OrderService orderService;

    @Autowired
    TokenService tokenService;

    /**
     * 添加一个未付款的订单
     */
    @PostMapping("insertOrder")
    public R insertOrder(@RequestBody OrderEntity orderEntity){

        /*orderEntity.setShippingCode(UUID.randomUUID().toString().replace("-", ""));
        orderEntity.setOrderId(System.currentTimeMillis()+""+UUID.randomUUID().toString().replace("-", ""));*/
        orderService.insertOrder(orderEntity);

        return R.ok("添加未付款订单信息成功",100);
    }

    /**
     * 修改订单的付款状态
     */
    @PostMapping("updateOrder")
    public R updateOrder(@RequestBody OrderEntity orderEntity){

        orderService.updateOrder(orderEntity);

        return R.ok("订单状态修改成功",100);
    }


    /**
     * 获取当前用户的订单列表
     */
    @PostMapping("getUserOrderList")
    public R getUserOrderList(@RequestBody Map map){
        Long userId = tokenService.getUserIdByToken((String) map.get("token"));
        map.put("userId",userId);

        List list = orderService.getUserOrderList(map);

        //判断订单中是否交易关闭
        for(int i = 0;i<list.size();i++){
            OrderEntity o = (OrderEntity) list.get(i);
            Date d = new Date();
            Long nowTime = d.getTime();
            Long closeTime = o.getCloseTime().getTime();
            if(nowTime > closeTime){
                OrderEntity orderEntity = new OrderEntity();
                orderEntity.setOrderId(o.getOrderId());
                orderEntity.setStatus("交易关闭");
                    orderService.updateOrder(orderEntity);
            }
        }
        List ss = orderService.getUserOrderList(map);

        return R.ok("",100).put("data",ss);
    }

    @PostMapping("getOrderInfo")
    public OrderEntity getOrderInfo(@RequestBody Map map){
        OrderEntity orderEntity = orderService.getOrderInfo(map);
        return orderEntity;
    }

}
